﻿using Autofac.Extras.DynamicProxy;
using Dapper;
using Microsoft.Win32.SafeHandles;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Truron.Purchase.Interface;
using Truron.Purchase.Model;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Service.DbContext;
using Truron.Purchase.Utility;
using Truron.Purchase.Utility.RedisHelper;

namespace Truron.Purchase.Service
{
    [Intercept(typeof(CustomAutofacAop))]
    public class FlowInstanceService:IFlowInstanceService
    {
        public void CreateFlow(FlowCreateParam param)
        {

            IDbModelService<Flow_Instance> db = new DbModelService<Flow_Instance>();
            IDbTransaction transaction = null;
            try
            {
               
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    //根据code查出流程模板
                    FlowScheme entity = conn.QueryFirstOrDefault<FlowScheme>("select * from Flow_Scheme where Code=@Code", new { Code = param.FlowCode },transaction);
                    List<Node> NodeList = new List<Node>();
                    FlowSchemeInfo flowSchemeInfo = new FlowSchemeInfo();
                    flowSchemeInfo = JsonConvert.DeserializeObject<FlowSchemeInfo>(entity.Scheme); ;
                    NodeList = flowSchemeInfo.nodes;
                    Node FirstNode = NodeList.Find(x => x.type == "start");
                    List<Flow_Instance> InstanceList = new List<Flow_Instance>();
                    Flow_Instance flowInstance = new Flow_Instance();
                    flowInstance.BussinessId = param.BussinessId;
                    flowInstance.CreateTime = DateTime.Now;
                    flowInstance.BtnCode = "";
                    flowInstance.FlowCode = param.FlowCode;
                    flowInstance.OperateById = param.UserInfo.UserId;
                    flowInstance.OperateByName = param.UserInfo.UserName;
                    flowInstance.OperateTime = DateTime.Now;
                    flowInstance.Notes = param.Notes;
                    flowInstance.NodeId = FirstNode.id;
                    flowInstance.NodeName = FirstNode.name;
                    if (param.IsNext == 0)
                    {
                        flowInstance.IsFinish = 0;
                        InstanceList.Add(flowInstance);
                    }
                    else if (param.IsNext == 1)
                    {
                        flowInstance.IsFinish = 1;
                        InstanceList.Add(flowInstance);
                        List<Node> nextNode = new List<Node>();
                        List<NextId> nextids = FirstNode.nextids;
                        for (int i = 0; i < nextids.Count; i++)
                        {
                            if (nextids[i].btncode == param.BtnCode)
                            {
                                if (nextids[i].condition == "")
                                {
                                    nextNode.Add(NodeList.Find(x => x.id == nextids[i].id));
                                }
                                //下面可以增加条件判断
                            }
                        }
                        //将nextnode的内容插入实例表
                        for (int i = 0; i < nextNode.Count; i++)
                        {
                            Flow_Instance flowInstance2 = new Flow_Instance();
                            flowInstance2.BussinessId = param.BussinessId;
                            flowInstance2.FlowCode = param.FlowCode;
                            flowInstance2.CreateTime = DateTime.Now;
                            flowInstance2.BtnCode = "";
                            //flowInstance2.OperateById = (int)nextNode[i].auditorid;
                            //flowInstance2.OperateByName = param.UserInfo.UserName;
                            //flowInstance2.OperateTime = DateTime.Now;
                            flowInstance2.Notes = "";
                            flowInstance2.NodeId = nextNode[i].id;
                            flowInstance2.NodeName = nextNode[i].name;
                            flowInstance2.IsFinish = 0;
                            InstanceList.Add(flowInstance2);
                        }
                    }

                    
                    for(int i=0;i<InstanceList.Count;i++)
                    {
                        db.InsertOne(InstanceList[i], conn, transaction);
                    }
                    if (param.IsNext == 1)
                    {
                        string sql = string.Format(" update {0} set FlowStatus=1 where Id={1} ",param.BussinessTable,param.BussinessId);
                        conn.Execute(sql, null,transaction);
                    }
                    transaction.Commit();
                }
            }
            catch(Exception ex)
            {
                transaction.Rollback();
            }
        }
        public void AuditFlow(FlowAuditParam param)
        {

            //寻找当前实例表中没有处理的那一条
            int FlowStatus = 1;
            List<Flow_Instance> InstanceList= DapperDbContext.Query<Flow_Instance>("select * from flow_instance where BussinessId=@BussinessId", new { BussinessId = param.BussinessId }).ToList();
            Flow_Instance CurrentTask = InstanceList.Find(x => x.NodeId == param.InstanceId);

            FlowScheme entity = DapperDbContext.QueryFirstOrDefault<FlowScheme>("select * from Flow_Scheme where Code=@Code", new { Code = CurrentTask.FlowCode });
            List<Node> NodeList = entity.Scheme.ToList<Node>();

            List<Node> nextNode = new List<Node>();
            Node CurrentNode = NodeList.Find(x => x.id == CurrentTask.NodeId);
            List<NextId> nextids = CurrentNode.nextids;

            for (int i = 0; i < nextids.Count; i++)
            {
                if (nextids[i].btncode == param.BtnCode)
                {
                    if (nextids[i].condition == "")
                    {
                        nextNode.Add(NodeList.Find(x => x.id == nextids[i].id));
                    }
                    //下面可以增加条件判断
                }
            }

            for (int i = 0; i < nextNode.Count; i++)
            {
                if(nextNode[i].type=="end")
                {
                    FlowStatus = 100;
                }
                Flow_Instance flowInstance2 = new Flow_Instance();
                flowInstance2.BussinessId = CurrentTask.BussinessId;
                flowInstance2.FlowCode = CurrentTask.FlowCode;
                flowInstance2.CreateTime = DateTime.Now;
                flowInstance2.BtnCode = "";
                flowInstance2.OperateById = param.UserInfo.UserId;
                flowInstance2.OperateByName = param.UserInfo.UserName;
                flowInstance2.OperateTime = DateTime.Now;
                flowInstance2.Notes = "";
                flowInstance2.NodeId = nextNode[i].id;
                flowInstance2.NodeName = nextNode[i].name;
                flowInstance2.IsFinish = 0;
                InstanceList.Add(flowInstance2);
            }
            IDbModelService<Flow_Instance> db = new DbModelService<Flow_Instance>();
            IDbTransaction transaction = null;
            try
            {

                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    for (int i = 0; i < InstanceList.Count; i++)
                    {
                        db.InsertOne(InstanceList[i], conn, transaction);
                    }
                    string sql = string.Format(" update {0} set FlowStatus={2},IsFinish=1,Notes='{3}',OperateTime=getdate() where Id={1} ", param.BussinessTable, param.BussinessId,FlowStatus,param.Notes);
                    conn.Execute(sql);
                    transaction.Commit();
                }
            }
            catch (Exception ex)
            {
                transaction.Rollback();
            }
        }
        public FlowInfo GetFlowInfo(int BussinessId)
        {
            try
            {
                FlowInfo flowInfo = new FlowInfo();
                List<Flow_Instance> InstanceList = DapperDbContext.Query<Flow_Instance>("select * from flow_instance where BussinessId=@BussinessId", new { BussinessId = BussinessId }).OrderBy(x => x.OperateTime).ToList();
                flowInfo.InstanceList = InstanceList;

                FlowScheme entity = DapperDbContext.QueryFirstOrDefault<FlowScheme>("select * from Flow_Scheme where Code=@Code", new { Code = InstanceList[0].FlowCode });
                flowInfo.schemeInfo = entity.Scheme.Replace("\r","").Replace("\n","");
                return flowInfo;
            }
            catch(Exception ex)
            {
                return null;
            }
        }
    }
}
